package core;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Adder extends UnitAbstract implements ActionListener {
	private double ratio0 = 1.0;
	private double ratio1 = 1.0;
	private transient DataPackage dataPack0;
	private transient DataPackage dataPack1;
	private transient JFrame frame;
	private transient JTextField ratio0Field;
	private transient JTextField ratio1Field;
	
	public Adder(){
		inputs = new String[]{"1","2"};
		outputs = new String[]{"O"};
	}

	public void read(DataPackage dataPack, String tPort) {
		if(dataPack0 == null && tPort.equals(inputs[0])){
			dataPack0=dataPack;
		}
		if(dataPack1 == null && tPort.equals(inputs[1])){
			dataPack1=dataPack;
		}
		if(dataPack0 != null && dataPack1 != null){
			if(dataPack1.sampleRate > dataPack0.sampleRate){
				DataPackage tempDP = dataPack0;
				dataPack0 = dataPack1;
				dataPack1 = tempDP;
			}
			double rate = dataPack1.sampleRate/dataPack0.sampleRate;
			for(int i=0; i<dataPack0.data.length; i++){
				dataPack0.data[i] = ratio0 * dataPack0.data[i] + ratio1 * dataPack1.data[(int) (i*rate)];
			}
			sendData(dataPack0);
			dataPack0 = null;
			dataPack1 = null;
		}
	}

	public void setRatio0(double ratio0) {
		this.ratio0 = ratio0;
	}
	public void setRatio1(double ratio1) {
		this.ratio1 = ratio1;
	}

	@Override
	public JFrame getFrame() {
		if(frame != null){
			return frame;
		}
		frame = new JFrame(toString());
		JPanel options = new JPanel();
		
		ratio0Field = new JTextField(""+this.ratio0);
		ratio1Field = new JTextField(""+this.ratio1);
		
		
		JButton applyButton = new JButton("Zastosuj");
		
		
		frame.setLayout(new BorderLayout());
		
		options = new JPanel();
		options.setLayout(new GridLayout(2,2));
		
		options.add(new Label("Ratio 0"));
		options.add(ratio0Field);
		options.add(new Label("Ratio 1"));
		options.add(ratio1Field);
		
		frame.add(BorderLayout.CENTER, options);
		
		applyButton.addActionListener(this);
		
		frame.add(BorderLayout.SOUTH, applyButton);
		frame.pack();
		frame.setLocationRelativeTo(null);
		return frame; //TODO
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		//TODO dodac walidacje danych
		this.ratio0 = Double.parseDouble( ratio0Field.getText() );
		this.ratio1 = Double.parseDouble( ratio1Field.getText() );
		
	}
	
	@Override
	public String toString() {
		return "Sumator";
	}
}
